<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //reduce
        var arr = [1, 2, 3, 4];
            var sum = arr.reduce(function (prev, cur, index, arr) {
                console.log(prev, cur, index);
                return prev + cur;
            })
            console.log(arr, sum);

            //
            var arr = [1, 2, 3, 4];
                var sum = arr.reduce(function (prev, cur, index, arr) {
                    console.log(prev, cur, index);
                    return prev + cur;
                },0) //注意这里设置了初始值 提供初始值通常更安全
                console.log(arr, sum);
                // 数组求和，求乘积
                var arr = [1, 2, 3, 4];
                    var sum = arr.reduce((x, y) => x + y)
                    var mul = arr.reduce((x, y) => x * y)
                    console.log(sum); //求和，10
                    console.log(mul); //求乘积，24
                //高级用法
                // 1.计算数组中每个元素出现的次数
                let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

                    let nameNum = names.reduce((pre, cur) => {
                        if (cur in pre) {
                            pre[cur]++
                        } else {
                            pre[cur] = 1
                        }
                        return pre
                    }, {})
                    console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}
            // 2.对象里的属性求和
            var result = [
                    {
                        subject: 'math',
                        score: 10
                    },
                    {
                        subject: 'chinese',
                        score: 20
                    },
                    {
                        subject: 'english',
                        score: 30
                    }
                ];

                var sum = result.reduce(function (prev, cur) {
                    return cur.score + prev;
                }, 0);
                console.log(sum) //60
    </script>
</body>
</html>